package com.pansoft.espcomp;

/**
 * lch
 * 7-15
 * webview
 */

import java.io.BufferedReader;
import java.io.InputStreamReader;

import android.app.ProgressDialog;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;

import com.efounder.constant.EnvironmentVariable;
import com.efounder.util.WebViewUtil;

public class ESPWebView extends WebView {
    JsToAndroidInterface jsToAndroidInterface;
    LoadInterface loadInterface;
    Context espContext;

    //ESPWebNotification espWebNotification ;
    public ESPWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        espContext = context;
        this.getSettings().setJavaScriptEnabled(true);
        //添加javascriptinterface，这个方法重要，this，和后面的string为js中调用android程序提供标志。
        this.addJavascriptInterface(this, "pansoft");
        this.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        /*** 打开本地缓存提供JS调用 **/
        getSettings().setDomStorageEnabled(true);
        // Set cache size to 8 mb by default. should be more than enough
        getSettings().setAppCacheMaxSize(1024 * 1024 * 8);
        // This next one is crazy. It's the DEFAULT location for your app's
        // cache
        // But it didn't work for me without this line.
        // UPDATE: no hardcoded path. Thanks to Kevin Hawkins
        String appCachePath = context.getApplicationContext().getCacheDir()
                .getAbsolutePath();
        getSettings().setAppCachePath(appCachePath);
        getSettings().setAllowFileAccess(true);
        getSettings().setAppCacheEnabled(true);

        //添加自己控制界面的js
        final String wholeJS = getFromAssets("self_define.js");
        //web.loadUrl(webUrl);
        post(new Runnable() {
            @Override
            public void run() {
                loadUrl("javascript:" + wholeJS);
            }
        });

        this.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && ESPWebView.this.canGoBack()) {  //表示按返回键 时的操作  
                        ESPWebView.this.goBack();   //后退
                        //webview.goForward();//前进   
                        return true;    //已处理     
                    }
                }
                return false;
            }
        });

    }

    //js android 交互标示的方法（无参数）
    public void jsToAndroid() {
        jsToAndroidInterface.jsToAndroid();
    }

    //js android 交互标示的方法（有参数）
    public void jsToAndroid(String xx) {
        ////////////jsToAndroidInterface.jsToAndroid(xx);
        if (xx.contains("esp")) {
            /*Toast.makeText(getApplicationContext(), "默认Toast样式",
	    		     Toast.LENGTH_SHORT).show();*/
            WebViewUtil.openEspUrl(xx);
        } else {
            ESPWebView.this.loadUrl(xx);
        }
    }

    public void getValueFromNative(String param) {
        String value = EnvironmentVariable.getProperty(param, "");
        System.out.println(param + value);
        //return  value;
    }

    //load回调
    public interface LoadInterface {
        public void load(String url);

        public void Reload(String url);
    }


    //js android 交互回调
    public interface JsToAndroidInterface {
        public void jsToAndroid();

        public void jsToAndroid(String xx);
    }

    public void setJsToAndroidInterface(JsToAndroidInterface jsToandroidInterface) {
        this.jsToAndroidInterface = jsToandroidInterface;
    }

    public void setLoadInterface(LoadInterface loadinterface) {
        this.loadInterface = loadinterface;
    }

    public String getFromAssets(String fileName) {
        try {
            InputStreamReader inputReader = new InputStreamReader(getResources().getAssets().open(fileName));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line = "";
            String Result = "";
            while ((line = bufReader.readLine()) != null)
                Result += line;
            return Result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
